package com.yuezhu.util;

import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.text.TextUtils;

import org.w3c.dom.Node;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串操作类 <br/>
 *
 * @version 1.0
 */
public final class StringUtil {

    private static final String TAG = "StringUtil";

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {

        String telRegex = "[1][358]\\d{9}";//"[1]"代表�?位为数字1�?[358]"代表第二位可以为3�?�?中的�?���?\\d{9}"代表后面是可以是0�?的数字，�?位�?
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 判断字符串是否为�?
     */
    public static boolean isEmpty(CharSequence s) {
        if ((s == null) || (s.length() <= 0) || s.equals("null") || s.equals("[\"\",\"\"]") || s.equals("[, ]") || s.equals("[]")) { // s.equals("null")
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否为�?
     */
    public static boolean isAnyEmpty(String... strs) {
        final int N = strs.length;
        for (int i = 0; i < N; i++) {
            if (isEmpty(strs[i]))
                return true;
        }

        return false;
    }

    /**
     * 从�?过column和cursor获取�?
     *
     * @param cursor
     * @param columnName
     * @return
     */
    public static String getString(Cursor cursor, String columnName) {
        int index = cursor.getColumnIndex(columnName);
        if (index != -1) {
            return cursor.getString(index);
        }
        return null;
    }

    /**
     * 判断两字符串是否相等
     *
     * @param s1
     * @param s2
     * @return
     */
    public static boolean equal(String s1, String s2) {
        if (s1 == s2) {
            return true;
        }
        if ((s1 != null) && (s2 != null)) {
            return s1.equals(s2);
        }
        return false;
    }

    public static String toString(Object obj) {
        if (obj == null)
            return "";
        else
            return obj.toString();
    }

    public static int toInt(Object obj) {
        if (obj == null || "".equals(obj) || "null".equals(obj)) {
            return 0;
        } else {
            try {
                return Integer.parseInt(obj.toString());
            } catch (Exception e) {
                return 0;
            }
        }
    }

    /**
     * 获取文件扩展�?
     *
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName) {
        int end = fileName.lastIndexOf('.');
        if (end >= 0) {
            return fileName.substring(end + 1);
        }
        return null;
    }

    /**
     * @param path
     * @return
     */
    public static String renameRes(String path) {
        if (path == null) {
            return null;
        }
        return path.replace(".png", ".a").replace(".jpg", ".b");
    }

    /**
     * 转null为空
     *
     * @param s
     * @return
     */
    public static String getNotNullString(String s) {
        if (s == null) {
            return "";
        }
        return s;
    }

    /**
     * 解析int
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static int parseInt(String str, int defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 解析long
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static long parseLong(String str, Long defaultValue) {
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 获得节点text
     *
     * @param node
     * @return
     */
    public static String getNodeText(Node node) {
        String text = null;
        Node tNode = node.getFirstChild();
        if ((tNode != null) && "#text".equals(tNode.getNodeName())) {
            text = tNode.getNodeValue();
            if (text != null) {
                text = text.trim();
            }
        }
        return text;
    }

    /**
     * 判断传入的字符串是否是数字类�?
     *
     * @param sNum
     * @return
     */
    public static boolean isNumberic(String sNum) {
        try {
            Float.parseFloat(sNum);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static boolean isNumberic(char c) {
        return isNumberic(String.valueOf(c));
    }

    /**
     * 判断字符是否在[a,z]、[A,Z]字母表中
     *
     * @param c
     * @return
     */
    public static boolean isCharacter(char c) {
        if (((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断某个字是否是汉字
     *
     * @param
     * @return
     */
    public static boolean isChinese(char s) {
        String regEx = "[\\u4e00-\\u9fa5]";
        return Pattern.matches(regEx, String.valueOf(s));
    }


    /**
     * 验证注册名称是否正确
     *
     * @param str
     * @return
     */
    public static boolean checkOnlyContainCharaterAndNumbers(String str) {
        Pattern p = Pattern.compile("^[!]+$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 验证密码是否合法 仅支持数字�?字母和符号，且密码中不能含有空格
     *
     * @param str
     * @return
     */
    public static boolean checkPwdIsValid(String str) {
        Pattern p = Pattern.compile("^[!-~]+$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 验证邮件地址格式是否正确
     *
     * @param str
     * @return
     */
    public static boolean checkValidMailAddress(String str) {
        Pattern p1 = Pattern.compile("\\w+@(\\w+\\.)+[a-z]{2,3}");
        Matcher m = p1.matcher(str);
        return m.matches();
    }

    /**
     * 获取非null的字符串
     *
     * @param str
     * @return 为null则返回空字符串，否则返回字符串本�?
     */
    public static String checkGetString(String str) {
        if (null == str)
            return "";
        return str;
    }

    /**
     * 根据ResolveInfo获取AppKey
     *
     * @param info
     * @return
     */
    public static String getAppKey(ResolveInfo info) {
        String appKey = (info.activityInfo.packageName + "|" + info.activityInfo.name)
                .toLowerCase();
        return appKey;
    }

    /**
     * 根据ComponentName获取AppKey
     *
     * @param info
     * @return
     */
    public static String getAppKey(ComponentName info) {
        String appKey = (info.getPackageName() + "|" + info.getClassName())
                .toLowerCase();
        return appKey;
    }

    /**
     * 根据ActivityInfo获取AppKey
     *
     * @param info
     * @return
     */
    public static String getAppKey(ActivityInfo info) {
        String appKey = (info.packageName + "|" + info.name).toLowerCase();
        return appKey;
    }

    /**
     * 文件后缀名过�?
     *
     * @param context
     * @param name
     * @param arrayId
     * @return
     */
    public static boolean checkSuffixsWithInStringArray(Context context,
                                                        String name, int arrayId) {
        String[] fileEndings = context.getResources().getStringArray(arrayId);
        for (String aEnd : fileEndings) {
            if (name.toLowerCase().endsWith(aEnd))
                return true;
        }
        return false;
    }

    /**
     * 过滤掉插入字符串中有特殊字符的字符换，返回合法的字符�?
     *
     * @param srcParam
     * @return
     */
    public static String filtrateInsertParam(CharSequence srcParam) {
        if (StringUtil.isEmpty(srcParam)) {
            LogUtils.e(TAG, "illegal sqlite param : " + srcParam);
            return "";
        }
        String result = srcParam.toString().replace("'", "''");
        result = result.replace("?", "");
        return result;
    }

    /**
     * 获取随机数，0 �?max之间 ，不包含max
     *
     * @param max
     * @return
     */
    public static int getRandom(int max) {
        return Integer
                .parseInt(String.valueOf(System.currentTimeMillis() % max));
    }

    public static String getPkgName(String component) {
        return component.substring(component.indexOf("{") + 1,
                component.lastIndexOf("/"));
    }

    public static String Utf8URLencode(String text) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if ((c >= 0) && (c <= 255)) {
                result.append(c);
            } else {
                byte[] b = new byte[0];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception ex) {
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    result.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return result.toString();
    }

    /**
     * 文件大小转换
     *
     * @param num
     * @param scale
     * @return
     */
    public static String parseLongToKbOrMb(long num, int scale) {
        float scaleNum;
        switch (scale) {
            case 0:
                scaleNum = 1;
                break;
            case 1:
                scaleNum = 10f;
                break;
            case 2:
                scaleNum = 100f;
                break;
            case 3:
                scaleNum = 1000f;
                break;
            case 4:
                scaleNum = 10000f;
                break;
            default:
                scaleNum = 1;
        }
        float n = num;
        if (n < 1024) {
            return Math.round(n * scaleNum) / scaleNum + "B";
        }
        n = n / 1024;
        if (n < 1024) {
            return Math.round(n * scaleNum) / scaleNum + "KB";
        }
        n = n / 1024;
        if (n < 1024) {
            return Math.round(n * scaleNum) / scaleNum + "MB";
        }
        n = n / 1024;
        return Math.round(n * scaleNum) / scaleNum + "GB";
    }

    /**
     * 将字节数转换为GB,MB,KB单位
     *
     * @param bytes
     * @param faction
     * @return
     */
    public static String getComputerSize(long bytes, int faction) {

        if (bytes / Math.pow(1000, 2) > 1000) // 以GB为单�?
            return formatNum2String(bytes / Math.pow(1000, 3), faction) + "GB";
        else if (bytes / 1000 > 1000) // 以MB为单�?
            return formatNum2String(bytes / Math.pow(1000, 2), faction) + "MB";
        else if (bytes / 1000 > 0) // 以KB为单�?
            return bytes / 1000 + "KB";
        else
            // 以B为单�?
            return bytes + "B";
    }

    /**
     * 格式化数字，并转成字符串�?
     *
     * @param num
     * @param faction
     * @return
     */
    public static String formatNum2String(double num, int faction) {
        NumberFormat numFormat = NumberFormat.getInstance();
        numFormat.setMinimumFractionDigits(faction);
        numFormat.setMaximumFractionDigits(faction);
        return numFormat.format(num);
    }

    /**
     * 检测是否是手机号
     *
     * @param strPhone
     * @return
     */
    public static boolean checkPhoneNumber(String strPhone) {

        String MOBILE = "^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
        String CM = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
        String CU = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
        String CT = "(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
        if (TextUtils.isEmpty(strPhone)) {
            return false;
        }

        if (strPhone.matches(MOBILE) || strPhone.matches(CM) || strPhone.matches(CU) || strPhone.matches(CT)) {
            return true;
        }
        return false;

    }

    /**
     * 将对象转成对应的字符�?
     *
     * @param obj
     * @return
     */
    public static String object2String(Object obj) {
        if (null == obj)
            return "";
        if (obj instanceof Integer) {
            return ((Integer) obj) + "";
        } else if (obj instanceof Float) {
            return ((Float) obj) + "";
        } else if (obj instanceof Double) {
            return ((Double) obj) + "";
        } else if (obj instanceof Boolean) {
            Boolean b = (Boolean) obj;
            return b ? "1" : "0";
        } else if (obj instanceof Byte) {
            return ((Byte) obj).toString();
        } else if (obj instanceof Short) {
            return ((Short) obj) + "";
        } else if (obj instanceof Long) {
            return ((Long) obj) + "";
        } else if (obj instanceof Character) {
            return ((Character) obj).toString();
        } else if (obj instanceof String) {
            return (String) obj;
        }
        return "";
    }

    /**
     * 隐藏电话号码�?-7�?
     *
     * @param phonestr
     * @return
     */
    public static String formatePhoneString(String phonestr) {
        return phonestr.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    public static String checkGetString(Context ctx, int nResID) {
        if (null == ctx || nResID <= 0) {
            return "";
        }

        return ctx.getString(nResID);
    }

    public static String toNormalString(String tmp) {
        if (null == tmp)
            return null;
        tmp = tmp.replaceAll("\n", "/n");
        return tmp;
    }

    public static String toSpecialString(String tmp) {
        if (null == tmp)
            return null;

        tmp = tmp.replaceAll("/n", "\n");
        return tmp;
    }

    // a chinese word equals one bytes, one character equals 0.5 byte
    public static String getLimitBytes(String str, int nMaxNum,
                                       AtomicReference<Integer> count) {
        if (isEmpty(str) || nMaxNum <= 0) {
            return "";
        }

        int nIndex = 0;
        float nCount = 0;
        boolean isLastChinese = false;
        char[] charArray = str.toCharArray();
        // Java判断�?��字符串是否有中文是利用Unicode编码来判断，
        // 因为中文的编码区间为�?x4e00--0x9fbb
        for (int i = 0; i < charArray.length; i++) {
            // if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
            if (charArray[i] > 255 || charArray[i] < 0) {
                nCount += 1;
                isLastChinese = true;
            } else {
                nCount += 0.5;
                isLastChinese = false;
            }
            nIndex += 1;
            if (nCount >= nMaxNum)
                break;
            // if(a>255 || a<0 ) 仅仅判断的是非英文字符，该条件得出的结果有中文字符有中文标点符号有日文和韩文
        }

        if (nCount > nMaxNum) {
            if (isLastChinese) {
                count.set((int) (nCount - 1));
            } else {
                count.set((int) nCount);
            }

            return str.substring(0, nIndex - 1);
        } else {
            count.set((int) nCount);
            return str.substring(0, nIndex);
        }
    }

    // a chinese word equals two bytes
    public static int getBytesNum(String str) {
        if (isEmpty(str)) {
            return 0;
        }

        int nCount = 0;
        char[] charArray = str.toCharArray();
        // Java判断�?��字符串是否有中文是利用Unicode编码来判断，
        // 因为中文的编码区间为�?x4e00--0x9fbb
        for (int i = 0; i < charArray.length; i++) {
            // if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
            if (charArray[i] > 255 || charArray[i] < 0) {
                nCount += 2;
            } else {
                nCount += 1;
            }
            // if(a>255 || a<0 ) 仅仅判断的是非英文字符，该条件得出的结果有中文字符有中文标点符号有日文和韩文
        }

        return nCount;
    }

    public static long checkGetLong(String str, long defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }

        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static String removeSpecStr(String str) {
        String strTemp = str.trim();
        if (StringUtil.isEmpty(strTemp)) {
            return "";
        }
        String dest = "";
        if (strTemp != null) {
            Pattern p = Pattern.compile("\t|\r|\n|\\\\");
            Matcher m = p.matcher(strTemp);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 替换字符串中的回车换行等字符
     *
     * @param source
     * @return
     */
    public static String replaceNewLine(String source) {
        Pattern CRLF = Pattern.compile("\r\n|\r|\n|\n\r|\t");
        Matcher m = CRLF.matcher(source);
        if (m.find()) {
            return m.replaceAll("");
        }
        return source;
    }

    /**
     * 替换html br tag
     *
     * @param source
     * @return
     */
    public static String replaceBRTag(String source) {
        Pattern p = Pattern.compile("<br>");
        Matcher m = p.matcher(source);
        if (m.find()) {
            return m.replaceAll(" ");
        }
        return source;
    }

    /**
     * 反编码字符串
     *
     * @param s
     * @param encode
     * @return
     */
    public static String checkDecoder(String s, String encode) {
        try {
            return URLDecoder.decode(s, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 字符串是否包含中�?
     *
     * @param s
     * @return
     */
    public static boolean isContainChinese(String s) {
        String str = getNotNullString(s);
        return str.getBytes().length != str.length();
    }

    public static boolean isSubjectEmpert(String str) {
        if (str.equals("[]")) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args, int i) {
        System.out.println(isSubjectEmpert("[]"));

    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static Long strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd�? HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate.getTime();
    }

    public static String getData(String data) {
        String line = "";
        line = data.replace("qanalysis", "qAnalysis").replace("qdocx", "qDocx").replace("qbody", "qBody").replace("qanswer", "qAnswer").replace("rightoption", "rightOption").replace("qoptions", "qOptions").replace("countoptions", "countOptions").replace("questiontype", "questionType").replace("subquestions", "subQuestions");
        return line;
    }

    public static boolean isBlank(String str) {
        if (str == null || str.trim().length() <= 0 || str.equalsIgnoreCase("null")) {
            return true;
        }
        return false;
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }


    /**
     * 处理正确次数
     *
     * @param correct
     * @return
     */
    public static String formatCorrectString(String correct) {
        String realCorrect = correct;
        if (realCorrect.contains(".")) {
//            realCorrect = String.format(realCorrect,"%.1f");
            BigDecimal b = new BigDecimal(Double.valueOf(correct));
            realCorrect = String.valueOf(b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
            if (realCorrect.endsWith(".0")) {
                realCorrect = realCorrect.replace(".0", "");
            }
        }
        return realCorrect;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    //判断email格式是否正确
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

    /**
     * 字符转译
     *
     * @param escape
     * @return
     */
    public static String Escape(String escape) {
//        if (escape.contains("+"))
//          escape=  escape.replace("+","%2B");
//        if (escape.contains("@"))
//            escape=   escape.replace("@","%40");
//        if (escape.contains(","))
//            escape=  escape.replace(",","%2C");
//        if (escape.contains(";"))
//            escape=  escape.replace(";","%3B");
//        if (escape.contains(">"))
//            escape=  escape.replace(">","%3E");
//        if (escape.contains("|"))
//            escape= escape.replace("|","%7C");
//        if (escape.contains("="))
//            escape= escape.replace("=","%3D");
//        if (escape.contains("/"))
//            escape= escape.replace("/","%2F");
//        return  escape;
        try {
            return URLEncoder.encode(escape, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return escape;
        }
    }
}
